﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DBProvider.Providers
{
	public class GroupProvider : IGroupProvider
	{
		#region IGroupProvider Members

		public Group CreateGroup(Group theNewGroup, out string msg)
		{
			if(theNewGroup == null)
			{
				throw new ArgumentNullException();
			}

			msg = string.Empty;
			Group result = null;

			try
			{
				using(DBHealthCommunityDataContext db = new DBHealthCommunityDataContext())
				{
					var isExist = db.Groups.Count(g => g.GroupName == theNewGroup.GroupName) > 0;

					if(isExist)
					{
						msg = "名称已存在";
					}
					else
					{
						db.Groups.InsertOnSubmit(theNewGroup);
						db.SubmitChanges();

						result = db.Groups.SingleOrDefault(g => g.GroupName == theNewGroup.GroupName);
					}
				}
			}
			catch(Exception exc)
			{
				throw exc;
			}

			return result;
		}

		public bool UpdateGroup(Group group)
		{
			if(group == null)
			{
				throw new ArgumentNullException();
			}

			var result = false;

			try
			{
				using(DBHealthCommunityDataContext db = new DBHealthCommunityDataContext())
				{
					var dbGroup = db.Groups.SingleOrDefault(g => g.GroupID == group.GroupID);

					if(dbGroup != null)
					{
						dbGroup.GroupName = group.GroupName;
						dbGroup.GroupRemark = group.GroupRemark;

						db.SubmitChanges();

						result = true;
					}
				}
			}
			catch(Exception exc)
			{
				throw exc;
			}

			return result;
		}

		public bool DeleteGroup(int groupID)
		{
			if(groupID <= 0)
			{
				throw new ArgumentOutOfRangeException();
			}

			var result = false;

			try
			{
				using(DBHealthCommunityDataContext db = new DBHealthCommunityDataContext())
				{
					var dbGroup = db.Groups.SingleOrDefault(g => g.GroupID == groupID);

					if(dbGroup != null)
					{
						db.Groups.DeleteOnSubmit(dbGroup);
						db.SubmitChanges();

						result = true;
					}
				}
			}
			catch(Exception exc)
			{
				throw exc;
			}

			return result;
		}

		public Group GetGroup(int groupID)
		{
			if(groupID <= 0)
			{
				throw new ArgumentOutOfRangeException();
			}

			Group result = null;

			try
			{
				using(DBHealthCommunityDataContext db = new DBHealthCommunityDataContext())
				{
					result = db.Groups.SingleOrDefault(g => g.GroupID == groupID);
				}
			}
			catch(Exception exc)
			{
				throw exc;
			}

			return result;
		}

		public List<Group> GetAllGroup()
		{
			List<Group> result = null;

			try
			{
				using(DBHealthCommunityDataContext db = new DBHealthCommunityDataContext())
				{
					var data = db.Groups;

					if(data != null)
					{
						result = data.ToList();
					}
				}
			}
			catch(Exception exc)
			{
				throw exc;
			}

			return result;
		}

		#endregion
	}
}
